<template>
  <a-modal v-model:visible="isShow" title="种子信息" okText="保存" @ok="doSave" :confirmLoading="loading">
    <a-alert :show-icon="false" message="种子文件和下载链接任选其一，种子文件优先。" />
    <a-form ref="form" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="种子名称" name="name">
        <a-input v-model:value="form.name" @blur="textTrim('name')" placeholder="可以不填，推送到下载器会自动获取" allow-clear/>
      </a-form-item>
      <a-form-item label="种子文件">
        <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
          <a-button size="small">
            <upload-outlined></upload-outlined>
            选择文件
          </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="下载链接" name="address">
        <a-textarea v-model:value="form.address" @blur="textTrim('address')" placeholder="可以推送到下载器进行下载" :rows="5" allow-clear/>
      </a-form-item>
      <a-form-item label="所属站点" name="siteid">
        <a-select
          v-model:value="form.siteid"
        >
          <a-select-option v-for="option in siteOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="所属分类" name="categoryid">
        <a-select
          v-model:value="form.categoryid"
        >
          <a-select-option v-for="option in categoryOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="描述" name="description">
        <a-textarea v-model:value="form.description" :rows="3"/>
      </a-form-item>
      <template v-if="!form.id">
      <a-divider orientation="left" class="extra-title">下载配置</a-divider>
      <a-form-item label="下载器" name="clientid">
        <a-select
          v-model:value="form.clientid"
        >
          <a-select-option v-for="option in clientOptions" :key="option.id" :value="option.id">
            {{ option.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="立即推送" name="startOnAdd">
        <a-switch v-model:checked="form.startOnAdd" />
      </a-form-item>
      <a-form-item label="是否开始" name="startNow">
        <a-switch v-model:checked="form.startNow" />
      </a-form-item>
      <a-form-item label="启用目录" >
        <a-checkbox v-model:checked="form.enableSiteFolder">站点目录</a-checkbox>
        <a-checkbox v-model:checked="form.enableCategoryFolder">分类目录</a-checkbox>
      </a-form-item>
      </template>
    </a-form>
  </a-modal>
</template>

<script>
import api from '../../api/api.js'
import { UploadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { ref } from 'vue';
export default {
  name: 'TorrentAdd',
  components: {
    UploadOutlined
  },
  props: {
    modelData: Object,
    success: Function,
    failure: Function,
    siteOptions: {
      type: Array,
      default: []
    },
    categoryOptions: {
      type: Array,
      default: []
    },
    clientOptions: {
      type: Array,
      default: []
    },
  },
  setup() {
    const fileList = ref([]);

    const handleRemove = file => {
      const index = fileList.value.indexOf(file);
      const newFileList = fileList.value.slice();
      newFileList.splice(index, 1);
      fileList.value = newFileList;
    };

    const beforeUpload = file => {
      const temp = file.name.split('.')
      if (temp.length > 0 && temp[temp.length - 1] === 'torrent') {
        // 只支持单个文件
        fileList.value = [file];
        // 支持多个文件  
        // fileList.value = [...fileList.value, file];
      } else {
        message.warn('请选择后缀名为".torrent"的文件')
      }
      return false;
    };

    return {
      fileList,
      handleRemove, beforeUpload

    }
  },
  data() {
    return {
      module: 'torrent',
      isShow: false, loading: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
      form: {
      },
      rules: {
        name: [
          { max: 100, message: '长度需100以内', trigger: 'blur' },
        ],
        // address: [
        //   { required: true, message: '请填写下载链接', trigger: 'blur' },
        //   { max: 1000, message: '长度需为1000以内', trigger: 'blur' },
        // ],
        description: [
          { max: 100, message: '长度需为100以内', trigger: 'blur' },
        ],
      }
    }
  },
  methods: {
    open(form) {
        this.form = {startOnAdd:false, startNow: false, enableSiteFolder: true, enableCategoryFolder: true, ...form}
        if (this.form.torrentFile) {
          this.fileList = [{
            uid: '-1',
            name: this.form.torrentFile,
            status: 'done',
            // url: 'http://www.baidu.com/xxx.png',
          }]
        } else {
          this.fileList = []
        }

        this.isShow = true
    },
    textTrim(col) {
      this.form[col] = this.form[col] ? this.form[col].trim() : ''
    //   console.log(`'${this.form[col]}'`)
    },
    handleUpload() {
    },
    doSave() {
      // console.log(this.fileList)
      if (this.fileList.length == 0 && !this.form.address) {
        this.$message.warn('种子文件和下载链接中，至少选择一项')
        return
      }
      this.$refs.form
      .validate()
      .then(async () => {
        this.loading = true
        // 上传种子文件
        // console.log(this.fileList[0])
        if (this.fileList && this.fileList.length > 0 && !this.fileList[0].status) {
          const formData = new FormData();
          formData.append('type', 'torrent')
          formData.append('file', this.fileList[0])
          // this.fileList.forEach(file => {
          //   formData.append('files[]', file);
          // });
          const uploadResp = await api.upload(formData);
          if (uploadResp.data.code === 1) {
            this.form.torrentFile = uploadResp.data.data.name 
          } else {
            this.$message.error(`上传失败：${uploadResp.data.message}`)
            this.loading = false
            return
          }
        }

        api.save(this.module, this.form).then(response => {
          if (response.data.code === 1) {
            this.isShow = false
            this.form = {}
            this.fileList = []
            this.$message.success('保存成功')
            // 回调
            this.$nextTick(()=>{
                this.success && this.success()
            })
          } else {
            this.$message.error(`保存失败：${response.data.message}`)
            // 
            this.failure && this.failure()
          }
        }).catch((error)=>{
          this.$message.error(`保存失败：${error.message}`)
        }).then(()=>{
          this.loading = false
        })

      })
      .catch(error => {
        console.log('error', error);
      })
    },
  }
}
</script>